package com.voicechat.firstmet.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.voicechat.firstmet.R;
import com.voicechat.firstmet.activity.PersonalHomepageActivity;
import com.voicechat.firstmet.adapter.ShareGirlsOrderAdapter;
import com.voicechat.firstmet.base.BaseFragment;
import com.voicechat.firstmet.bean.MySelfInfoBean;
import com.voicechat.firstmet.bean.ShareGirlsOrderBean;
import com.voicechat.firstmet.dialog.AlertDialog;
import com.voicechat.firstmet.net.HTTPAPI;
import com.voicechat.firstmet.net.service.FaintService;
import com.voicechat.firstmet.utils.ParcelableUtils;
import com.voicechat.firstmet.utils.PhoneUtils;
import com.voicechat.firstmet.utils.SPUtils;
import com.voicechat.firstmet.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ProjectName: FirstMet
 * @Package: com.voicechat.firstmet.fragment
 * @ClassName: BlindDateOrderFragment
 * @Description: 我接收到的订单页面
 * @Author: ljp
 * @CreateDate: 2019/1/19 11:31
 * @Version: 1.0
 */
public class MyReceiveShareGirlsOrderFragment extends BaseFragment {
    @BindView(R.id.recycler_list)
    RecyclerView recyclerList;
    @BindView(R.id.smart_refresh)
    SmartRefreshLayout smartRefresh;
    @BindView(R.id.default_image_view)
    ImageView defaultImageView;
    @BindView(R.id.default_text_view)
    TextView defaultTextView;
    @BindView(R.id.linear_layout)
    LinearLayout linearLayout;
    private MySelfInfoBean.ObjectBean mySeleInfo;
    private String token;
    private String deviceInfo;
    private List<ShareGirlsOrderBean.PageBean.ListBean> listBeans;
    private int page;
    private ShareGirlsOrderAdapter shareGirlsOrderAdapter;
    private String TAG = "MyReceiveShareGirlsOrderFragment";
    private AlertDialog myDialog;

    public static MyReceiveShareGirlsOrderFragment newInstance() {
        Bundle args = new Bundle();
        MyReceiveShareGirlsOrderFragment fragment = new MyReceiveShareGirlsOrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int loadLayout() {
        return R.layout.fragment_my_share_girls;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        ButterKnife.bind(this, view);

        mySeleInfo = MySelfInfoBean.ObjectBean.CREATOR.createFromParcel(ParcelableUtils.unmarshall(
                SPUtils.getEditoString(SPUtils.SP_MYSELFINFO)));
        token = SPUtils.getEditoString(SPUtils.SP_TOKEN);
        deviceInfo = PhoneUtils.getDeviceInfo(context);
        myDialog = new AlertDialog(context).builder();
        initView();
    }

    TextView textvCancel;
    TextView textvSure;

    /**
     * @return
     * @method
     * @description 数据控件实例化
     * @date: 2019/1/4 20:00
     * @author: ljp
     */
    private void initView() {
        listBeans = new ArrayList<>();
        smartRefresh.autoRefresh();
        //下拉刷新
        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                initHttp();
                smartRefresh.finishRefresh(10000);
            }
        });
        //上拉加载更多
        smartRefresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                initHttp();
                smartRefresh.finishLoadMore(10000);
            }
        });
        //设置 Header 为 贝塞尔雷达 样式
        smartRefresh.setRefreshHeader(new ClassicsHeader(context));
        smartRefresh.setRefreshFooter(new ClassicsFooter(context));
        shareGirlsOrderAdapter = new ShareGirlsOrderAdapter(context, listBeans, R.layout.item_blind_date_order, "receive");
        recyclerList.setLayoutManager(new LinearLayoutManager(context));
        recyclerList.setAdapter(shareGirlsOrderAdapter);
        shareGirlsOrderAdapter.setOrderOnClick(new ShareGirlsOrderAdapter.OrderOnClick() {
            @Override
            public void setPlaceOrderOnClick(ShareGirlsOrderBean.PageBean.ListBean listBean, int flag, TextView textViewCancel, TextView tvSure) {
            }

            @Override   //接收订单者  //2接收  1拒绝   3取消订单
            public void setReceiveOrderOnClick(ShareGirlsOrderBean.PageBean.ListBean listBean, int flag, TextView textViewCancel, TextView tvSure) {
                Log.i(TAG, "setReceiveOrderOnClick: ---flag-------" + flag);
                textvSure = tvSure;
                textvCancel = textViewCancel;
                switch (flag) {
                    case 1://接单状态 0初始值 1拒绝 2同意
                        textvSure.setEnabled(false);
                        initDialog(listBean);
                        break;
                    case 2:
                        textvSure.setEnabled(false);
                        acceptRejectionOrder(listBean, 2);
                        break;
                    case 3:
                        myDialog.setGone().setMsg(getResources().getString(R.string.place_accept_cancel)).
                                setNegativeButton("再想想", R.color.colorAccent, null).
                                setPositiveButton("确定", R.color.colorAccent, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        completeCancelOrder(listBean, 3);
                                    }
                                }).show();

                        break;
                }
            }

            @Override
            public void setPerson(ShareGirlsOrderBean.PageBean.ListBean listBean) {
                Intent intent = new Intent(context, PersonalHomepageActivity.class);
                intent.putExtra("anchorId", listBean.getUserId());
                context.startActivity(intent);
            }
        });
        initHttp();
    }

    /**
     * @return
     * @method
     * @description 拒绝
     * @date: 2019/1/29 10:02
     * @author: ljp
     */
    private void initDialog(ShareGirlsOrderBean.PageBean.ListBean listBean) {
        myDialog.setGone().setMsg(getResources().getString(R.string.receive_accept_reject)).
                setNegativeButton("再考虑下", R.color.colorAccent, null).
                setPositiveButton("拒绝", R.color.colorAccent, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        acceptRejectionOrder(listBean, 1);
                    }
                }).show();
    }

    /**
     * @return
     * @method
     * @description 接受/拒绝订单
     * @date: 2019/1/26 11:24
     * @author: ljp
     */
    private void acceptRejectionOrder(ShareGirlsOrderBean.PageBean.ListBean listBean, int i) {
        FaintService.acceptRejectionOrder(token, deviceInfo, listBean.getId(), listBean.getRmb(), i).subscribe(result -> {
            Log.i(TAG, "completeCancelOrder: ----------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {//接单状态 0初始值 1拒绝 2同意
                textvSure.setEnabled(true);
                toast_MakeText(result.getMsg());
                if (i == 1) {
                    listBean.setComplete(3);
                    shareGirlsOrderAdapter.notifyDataSetChanged();
                } else if (i == 2) {//接受跳转到聊天页面
                    //IMChatActivity.navToChat(context, listBean.getUserId(), listBean.getNickName(), String.valueOf(listBean.getType()),"");
                    // listBean.setReceiptStatus(2);
                    //shareGirlsOrderAdapter.notifyDataSetChanged();
                }
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                textvSure.setEnabled(true);
                Utils.setToken(context);
            } else {
                textvSure.setEnabled(true);
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            textvSure.setEnabled(true);
            Log.i(TAG, "completeCancelOrder: ----------" + throwable.toString());
        });
    }

    /**
     * @return
     * @method
     * @description 取消/完成订单
     * @date: 2019/1/26 11:24
     * @author: ljp
     */
    private void completeCancelOrder(ShareGirlsOrderBean.PageBean.ListBean listBean, int i) {
        FaintService.completeCancelOrder(token, deviceInfo, listBean.getId(), i, listBean.getRmb()).subscribe(result -> {
            Log.i(TAG, "completeCancelOrder: ----------" + result.toString());
            if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                listBean.setComplete(3);
                shareGirlsOrderAdapter.notifyDataSetChanged();
            } else if (result.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(result.getMsg());
            }
        }, throwable -> {
            Log.i(TAG, "completeCancelOrder: ----------" + throwable.toString());
        });
    }

    /**
     * @return
     * @method
     * @description 网络请求
     * @date: 2019/1/23 16:12
     * @author: ljp
     */
    private void initHttp() {
        FaintService.selectShareGirlsReceiveOrder(token, deviceInfo, mySeleInfo.getId()).subscribe(shareGirlsOrderBean -> {
            if (shareGirlsOrderBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETRUN_SUCCESS) {
                int i = shareGirlsOrderBean.getPage().getCount() / shareGirlsOrderBean.getPage().getPageSize() +
                        (shareGirlsOrderBean.getPage().getCount() % shareGirlsOrderBean.getPage().getPageSize() == 0 ? 0 : 1);
                if (i != 0 && page > i) {//判断是否是最后一页
                    smartRefresh.finishLoadMoreWithNoMoreData();//完成加载并标记没有更多数据 1.0.4
                } else {
                    if (page == 1) {
                        listBeans.clear();
                        smartRefresh.finishRefresh();
                    }
                    if(shareGirlsOrderBean.getPage().getList() != null) {
                        linearLayout.setVisibility(View.GONE);
                        listBeans.addAll(shareGirlsOrderBean.getPage().getList());
                        shareGirlsOrderAdapter.notifyDataSetChanged();
                        smartRefresh.setVisibility(View.VISIBLE);
                        smartRefresh.finishLoadMore();
                    }else {
                        smartRefresh.setVisibility(View.GONE);
                        linearLayout.setVisibility(View.VISIBLE);
                    }
                    smartRefresh.finishLoadMore();
                }
            } else if (shareGirlsOrderBean.getCode() == HTTPAPI.RETURN_CODE_TYPE.RETURN_NO_TOKEN) {
                Utils.setToken(context);
            } else {
                toast_MakeText(shareGirlsOrderBean.getMsg());
            }
        }, throwable -> {
            toast_MakeText(getResources().getString(R.string.net_error));
        });

    }


}
